#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

int sfp,nfp;
socklen_t sin_size;
struct sockaddr_in s_add,c_add;
unsigned short portnum=0x8888;

void do_file_transfer();

int main(int argc, char *argv[])
{
	/*
	if (daemon(0, 0)) {//调用glibc库函数daemon,创建daemon守护进程
		perror("daemon");
		return -1;
	}
	*/

	printf("Hello,welcome to my server !\r\n");
	sfp = socket(PF_INET, SOCK_STREAM, 0);
	if(-1 == sfp) {
		printf("socket fail ! \r\n");
		return -1;
	}
	printf("socket ok !\r\n");


	bzero(&s_add,sizeof(struct sockaddr_in));
	s_add.sin_family=PF_INET;
	s_add.sin_addr.s_addr=htonl(INADDR_ANY);
	s_add.sin_port=htons(portnum);

	if(-1 == bind(sfp,(struct sockaddr *)(&s_add), sizeof(struct sockaddr))) {
		printf("bind fail !\r\n");
		return -1;
	}
	printf("bind ok !\r\n");

	if(-1 == listen(sfp,5)) {
		printf("listen fail !\r\n");
		return -1;
	}
	printf("listen ok\r\n");
	for (int i = 0; i < 500; i++) {
		int pid;
		if (0 != (pid = fork())) {
			//Father Process.
		} else {
			//Child Process.
			printf("%d\n", getpid());
			do_file_transfer();
			close(sfp);
			exit(0);
		}
	}
	return 0;
}

void do_file_transfer()
{
	while(1) {
		sin_size = sizeof(struct sockaddr_in);

		nfp = accept(sfp, (struct sockaddr *)(&c_add), &sin_size);
		if(-1 == nfp) {
			printf("accept fail !\r\n");
			return;
		}
		printf("accept ok!\r\nServer start get connect from %#x : %#x\r\n",ntohl(c_add.sin_addr.s_addr),ntohs(c_add.sin_port));


		if(-1 == write(nfp,"hello,welcome to my server \r\n",32)) {
			printf("write fail!\r\n");
			return;
		}
		printf("write ok by %d !\r\n", getpid());

		char buf[1024];
		int fd;

		mkdir("/home/zhangxp/BackUp", 0777);
		chdir("/home/zhangxp/BackUp");
			

		//time_t t;
		//time(&t);
		char file_name[32];
		char *p = file_name;
		while (read(nfp, p, 1)) {
			if (*p == '\n')
				break;
			p++;
		}
		*(p++) = '\0';
		//sprintf(file_name, "TestFtp_%ld",t );
		printf("%s\n", file_name);
		fd = open(file_name, O_CREAT | O_WRONLY);
		int total = 0;
		while (int nread = read(nfp, buf, sizeof(buf))) {
			buf[nread] = '\0';
			printf("%s\n", buf);
			write(fd, buf, nread);
			total += nread;
		}
		if (!total)
			unlink(file_name);
		close(fd);

		close(nfp);

	}
}

